package com.zigong.app.base;

import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.gridsum.videotracker.GSVideoState;
import com.gridsum.videotracker.VideoTracker;
import com.gridsum.videotracker.entity.LiveMetaInfo;
import com.gridsum.videotracker.entity.MetaInfo;
import com.gridsum.videotracker.entity.VideoInfo;
import com.gridsum.videotracker.entity.VodMetaInfo;
import com.gridsum.videotracker.play.LivePlay;
import com.gridsum.videotracker.play.Play;
import com.gridsum.videotracker.play.VodPlay;
import com.gridsum.videotracker.provider.IInfoProvider;
import com.gridsum.videotracker.provider.ILiveInfoProvider;
import com.gridsum.videotracker.provider.IVodInfoProvider;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.ijkplaylib.widget.GPlayerView;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.ui.dialog.NetModeDiaFragment;
import com.zigong.app.ui.utils.FloatGSYVideoUtils;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.OnFullClick;
import com.zigong.app.ui.utils.SampleListener;
import com.zigong.app.ui.widget.BasePlayerView;
import com.shuyu.gsyvideoplayer.listener.INetPromt;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static com.zigong.app.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.zigong.app.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * Created by rh008 on 2017/7/17.
 */

public class BaseCanPlayActivity extends BaseDetailActivity implements IMediaPlayer.OnInfoListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnPreparedListener {

    protected FloatGSYVideoUtils floatVideoUtils;

    protected boolean isPortrait = true;

    protected final String Action_Net_Change = "android.net.conn.CONNECTIVITY_CHANGE";
    protected NetModeDiaFragment netModeDiaFragment;
    public static final String NET_TAG = "dia_net_mode_fragment";
    protected String contentVideoUrl;
    protected View playView;

    private boolean isAutoRotation = false;

    protected OrientationUtils orientationUtils;

    protected boolean isVideoTop = true;

    private boolean hasRegistNetReciever;
    private VideoTracker tracker = null;
    private IInfoProvider infoProvider = null;
    private Play play = null;
    private IjkMediaPlayer mediaPlayer;
    protected SampleListener videoListener = new SampleListener() {
        @Override
        public void onPrepared(String url, Object... objects) {
            super.onPrepared(url, objects);
            onPlayPrepare(url, objects);
        }

        @Override
        public void onClickBlank(String url, Object... objects) {
            super.onClickBlank(url, objects);
        }

        @Override
        public void onQuitFullscreen(String url, Object... objects) {
            super.onQuitFullscreen(url, objects);
            if (orientationUtils != null) {
                orientationUtils.backToProtVideo();
            } else {
                actionToPortrait();
            }
        }

        @Override
        public void onEnterFullscreen(String url, Object... objects) {
            super.onEnterFullscreen(url, objects);
        }

        @Override
        public void onAutoComplete(String url, Object... objects) {
            super.onAutoComplete(url, objects);

        }
    };

//    private BroadcastReceiver netRecieve = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String a = intent.getAction();
//            JLog.e("action=" + a);
//            if (Action_Net_Change.equals(a)) {
//                recieveNetBrodcast();
//            }
//        }
//    };

    BaseDialogFragment.ICallBack netBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
//                floatVideoUtils.stopVideoView();
            } else if (msg.what == OK_TAG) {
//                floatVideoUtils.setLiving(false).play(img, mVideoUrl);
//                if (topController != null) {
//                    topController.setTitle(titleTemp);
//                }
                Cache.getInstance().setCheckNet(true);
                onNetPromptCallBacked(true);
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        IntentFilter inf = new IntentFilter(Action_Net_Change);
//        registerReceiver(netRecieve, inf);
        hasRegistNetReciever = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (floatVideoUtils != null) {
            floatVideoUtils.onResume();
        }
        if (orientationUtils != null && canEnableOrientationWhenResume()) {
            orientationUtils.setEnable(true);
        }
        if (play != null) {
            play.setVisibility(true);
        }
    }

    @Override
    protected void onPause() {
        if (floatVideoUtils != null) {
            floatVideoUtils.onPause();
        }
        if (orientationUtils != null) {
            orientationUtils.setEnable(false);
        }
        if (play != null) {
            play.setVisibility(false);
        }
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }

        if (StandardGSYVideoPlayer.backFromWindowFull(this)) {
            actionToPortrait();
            return;
        }
        super.onBackPressed();
//        if (floatVideoUtils == null || !floatVideoUtils.onBackPress()) {
//            super.onBackPressed();
//        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
        if (floatVideoUtils != null) {
            floatVideoUtils.onConfigurationChanged(this, newConfig, orientationUtils);
        }
        if (isPortrait) {
            onChangedToPortrait(newConfig);
        } else {
            onChangedToLandscape(newConfig);
        }
    }

    @Override
    protected void onDestroy() {
        Glide.with(getApplicationContext()).pauseRequests();
        if (floatVideoUtils != null) {
            floatVideoUtils.onDestory();
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
        if (getVideoPlayer() != null) {
            getVideoPlayer().release();
        }
        if (play != null) {
            play.endPlay();
        }
//        try {
//            if (netRecieve != null && hasRegistNetReciever) {
//                unregisterReceiver(netRecieve);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        super.onDestroy();

    }

    protected boolean canEnableOrientationWhenResume() {
        return floatVideoUtils != null && floatVideoUtils.isShowing();
    }

    protected void onPlayPrepare(String url, Object... objects) {
        if (orientationUtils != null && canEnableOrientationWhenResume()) {
            orientationUtils.setEnable(true);
        }
        if (floatVideoUtils != null) {
            floatVideoUtils.setPlayed(true);
        }
    }

    /**
     * 是否在视频准备时可以开放自动转屏
     *
     * @return
     */
    protected boolean canEnableOrientationWhenPrepare() {
        return true;
    }

    protected int getCurrentScrollY() {
        return 0;
    }

    protected boolean isShouldMuteStart() {
        return false;
    }

    protected int actionPlay(@NonNull BasePlayerView player, @NonNull String url, String title, String imgUrl, boolean playNow) {
        if (TextUtils.equals(player.getOriUrl(), url) && player.getCurrentState() != BasePlayerView.CURRENT_STATE_PLAYING) {
            player.startPlay();
            return 0;
        }

        player.setUp(url, false, title);

        if (isShouldMuteStart()) {
            player.setMute(true);
        }
        if (playNow) {
            player.startPlay();
        }
        if (player.getThumbImge() != null && !this.isFinishing() && !this.isDestroyed()) {
            if (!TextUtils.isEmpty(imgUrl) && Util.isOnMainThread()) {
                GlideUtil.getGlideWithLarge169DefNotFit(this, imgUrl).into(player.getThumbImge());
            } else {
                player.getThumbImge().setImageResource(R.mipmap.icon_def_16_9_l);
            }
        }
        return 1;
    }

    protected void onChangedToPortrait(Configuration newConfig) {
    }

    protected void onChangedToLandscape(Configuration newConfig) {
    }

    protected void enableAutoRotation() {
//        if (isPortrait) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
//        } else {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
//        }
        if (orientationUtils != null) {
            orientationUtils.setEnable(true);
        }
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        isAutoRotation = true;
    }

    protected void disableAutoRotation() {
//        if (isPortrait) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        } else {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
        if (orientationUtils != null) {
            orientationUtils.setEnable(false);
        }
        isAutoRotation = false;
    }

    protected boolean isAutoRotation() {
        return isAutoRotation;
    }

    public void setAutoRotation(boolean autoRotation) {
        if (autoRotation != this.isAutoRotation) {
            if (autoRotation) {
                enableAutoRotation();
            } else {
                disableAutoRotation();
            }
        }
    }

    protected void actionToPortrait() {
        if (!isPortrait) {
            if (isAutoRotation) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }
    }

    protected void actionToLandscape() {
        if (isPortrait) {
            if (isAutoRotation) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
    }

    protected void initVideoPlayer(@NonNull BasePlayerView player, VideoInfo info, boolean isLiving) {
//        JLog.e("hhah  player="+player+"  float="+floatVideoUtils+"   ori="+orientationUtils+"\n "+videoListener);
        initGSMCode(isLiving, info);
        if (floatVideoUtils != null) {
            floatVideoUtils.setSampleListener(videoListener);
            floatVideoUtils.setOninfoListener(this);
            floatVideoUtils.setOnCompletionListener(this);
            floatVideoUtils.setOnPreparedListener(this);

        } else {
            player.setStandardVideoAllCallBack(videoListener);
            player.setOninfoListener(this);
            player.setOnPreparedListener(this);
            player.setOnCompletionListener(this);
        }
        if (orientationUtils == null) {
//            orientationUtils = new OrientationUtils(this, player);
//            orientationUtils.setRotateWithSystem(false);
        }
        player.setFullClick(new OnFullClick() {
            @Override
            public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
                onFullClicked(player, isLandscape);
            }
        });
        player.setNetPromt(new INetPromt() {
            @Override
            public boolean onNetPromt() {
                showNetProt();
                return false;
            }
        });
    }

    protected void initVideoPlayer(@NonNull BasePlayerView player, VideoInfo info, boolean isLiving, final OnPlayerFullClickListener full) {
//        JLog.e("hhah  player="+player+"  float="+floatVideoUtils+"   ori="+orientationUtils+"\n "+videoListener);
        initGSMCode(isLiving, info);
        if (floatVideoUtils != null) {
            floatVideoUtils.setSampleListener(videoListener);
            floatVideoUtils.setOninfoListener(this);
            floatVideoUtils.setOnCompletionListener(this);
            floatVideoUtils.setOnPreparedListener(this);

        } else {
            player.setStandardVideoAllCallBack(videoListener);
            player.setOninfoListener(this);
            player.setOnPreparedListener(this);
            player.setOnCompletionListener(this);
        }
        if (orientationUtils == null) {
//            orientationUtils = new OrientationUtils(this, player);
//            orientationUtils.setRotateWithSystem(false);
        }
        player.setFullClick(new OnFullClick() {
            @Override
            public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
                if (null != full) {
                    full.onFullClick(isLandscape);
                }
                onFullClicked(player, isLandscape);
            }
        });
        player.setNetPromt(new INetPromt() {
            @Override
            public boolean onNetPromt() {
                showNetProt();
                return false;
            }
        });
    }

    protected boolean initFloatVideoUtils(View parentView, AbsoluteLayout videoLayout, int otherHeight, final VideoInfo info) {
        if (floatVideoUtils == null) {
            floatVideoUtils = new FloatGSYVideoUtils(this, parentView, videoLayout, otherHeight);
            floatVideoUtils.setPlayerFactor(new FloatGSYVideoUtils.IPlayerFactor() {
                @Override
                public BasePlayerView createPlayerView() {
                    BasePlayerView pl = createdPlayerView();
                    initVideoPlayer(pl, info, true);
                    return pl;
                }
            });
//            if (playerView != null) {
//                initVideoPlayer(playerView);
//
//                playerView.setRotateWithSystem(false);
//                playerView.setRotateViewAuto(false);
//
////                playerView.setStandardVideoAllCallBack(videoListener);
////                if (orientationUtils == null) {
////                    orientationUtils = new OrientationUtils(this, playerView);
////                    orientationUtils.setRotateWithSystem(false);
////                }
////                floatVideoUtils.setPlayerView(initVideoPlayer());
//                floatVideoUtils.showPlayer(parentView, false);
//            }
            return true;
        }
        return false;
    }

    @NonNull
    protected BasePlayerView createdPlayerView() {
        return new BasePlayerView(this);
    }

    protected boolean isDataGetting() {
        return false;
    }

    protected void onFullClicked(StandardGSYVideoPlayer player, boolean isLandscape) {
        if (player == null || TextUtils.isEmpty(player.getOriUrl())) {
            if (isDataGetting()) {
                toast(R.string.loading_data_wait);
            } else {
                toast(R.string.data_wrong);
            }
            return;
        }
        if (isLandscape) {
            player.setHideKey(false);
            if (orientationUtils != null) {
                orientationUtils.backToProtVideo();
            } else {
                actionToPortrait();//切换为竖屏
            }
            StandardGSYVideoPlayer.backFromWindowFull(this);
        } else {
            player.setHideKey(true);
            if (orientationUtils != null) {
                orientationUtils.resolveByClick();
            } else {
                //判断视频源是横屏还是竖屏的，弱势竖屏的，就不转向
                if (player.getWidthToHeightRatio() == 0 || player.getWidthToHeightRatio() > 1) {
                    //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                    actionToLandscape();//在这切换为横屏
                }
            }
            player = (StandardGSYVideoPlayer) player.startWindowFullscreen(this, true, true);
            if (player != null) {
                player.getBackButton().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });
            }
        }
    }

    /**
     * 提示用户网络情况
     */
    private void showNetProt() {
        if(Cache.getInstance().isCheckNet()){
            onNetPromptCallBacked(true);
            return;
        }
        if (netModeDiaFragment == null) {
            netModeDiaFragment = new NetModeDiaFragment();
        }
        if (fragmentDialogShowHelper != null && !fragmentDialogShowHelper.isResuming()) {
            return;
        }
        if (!netModeDiaFragment.isAdded()) {
            netModeDiaFragment.setCallBack(netBack);
            netModeDiaFragment.show(getSupportFragmentManager(), NET_TAG);
        }
    }

    protected BasePlayerView initVideoPlayer() {
        return null;
    }

    protected StandardGSYVideoPlayer getVideoPlayer() {
        return null;
    }

    protected void recieveNetBrodcast() {
        int netmode = NetModeUtil.GetNetype(this);
        if (netmode == 1) {
            if (floatVideoUtils != null && floatVideoUtils.isPlaying()) {
                // showNetDialog();
//                floatVideoUtils.getPlayerView().pausePlay();
                floatVideoUtils.pausePlay();
            }
            whenNetReceiveToPause();
        } else if (netmode >= 1) {
            if (netModeDiaFragment != null && netModeDiaFragment.isShowing()) {
                netModeDiaFragment.dismissAllowingStateLoss();
                onNetPromptCallBacked(true);
            }
        }
    }

    public void onNetPromptCallBacked(boolean isContinue) {
        if (floatVideoUtils != null) {
            if (isContinue) {
                StandardGSYVideoPlayer player = getVideoPlayer();
                if (player != null) {
                    player.startPlayLogic();
                }
            } else {
                floatVideoUtils.stopVideoView(false);
            }
        }
    }

    public void setSampleVideoListener(SampleListener listener) {
        if (getVideoPlayer() != null && listener != null && listener != videoListener) {
            listener.setInternal(videoListener);
            getVideoPlayer().setStandardVideoAllCallBack(listener);
        }
    }

    protected void whenNetReceiveToPause() {
    }

    protected void onPlayerConstructor(GPlayerView playerView, ViewGroup base) {
    }

    protected void onChangeToPlaying() {
    }

    protected void onChangeToStop() {
    }

    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int i1) {
        if (iMediaPlayer != null && mediaPlayer == null) {
            mediaPlayer = (IjkMediaPlayer) iMediaPlayer;
        }
        if (play == null) {
            return false;
        }
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            Log.e("onInfo", "MEDIA_INFO_BUFFERING_START");
            play.onStateChanged(GSVideoState.BUFFERING);
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            Log.e("onInfo", "MEDIA_INFO_BUFFERING_END");
            play.onStateChanged(GSVideoState.PLAYING);
        } else if (what == IMediaPlayer.MEDIA_INFO_MEDIA_ACCURATE_SEEK_COMPLETE) {
            play.onStateChanged(GSVideoState.SEEKING);
        }
        return false;
    }

    @Override
    public void onCompletion(IMediaPlayer iMediaPlayer) {
        if (play != null) {
            if (play instanceof VodPlay) {
                VodMetaInfo metaInfo = new VodMetaInfo();
                metaInfo.setBitrateKbps((int) iMediaPlayer.getMediaInfo().mMeta.mBitrate);
                metaInfo.videoDuration = iMediaPlayer.getDuration() / 1000.0f;
                metaInfo.setIsBitrateChangeable(false);
                ((VodPlay) play).endPerparing(true, metaInfo);
            } else if (play instanceof LivePlay) {
                LiveMetaInfo metaInfo = new LiveMetaInfo();
                metaInfo.setBitrateKbps((int) iMediaPlayer.getMediaInfo().mMeta.mBitrate);
                metaInfo.setIsBitrateChangeable(false);
                ((LivePlay) play).endPerparing(true, metaInfo);
            }
        }

    }

    @Override
    public void onPrepared(IMediaPlayer iMediaPlayer) {
        if (play != null) {
            play.beginPerparing();
        }
    }
//    protected void showNetDialog() {
//        if (netModeDiaFragment == null) {
//            netModeDiaFragment = new NetModeDiaFragment();
//        }
//        netModeDiaFragment.setCallBack(netCallBack);
//        safeShowDialog(netModeDiaFragment, NET_TAG);
//    }
//
//
//    BaseDialogFragment.ICallBack netCallBack = new BaseDialogFragment.ICallBack() {
//        @Override
//        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
//            if (msg.what == NO_TAG) {
//                floatVideoUtils.stopVideoView();
//            } else if (msg.what == OK_TAG) {
//                floatVideoUtils.play(playView, contentVideoUrl);
//            }
//        }
//    };


    private void initGSMCode(boolean isLiving, VideoInfo info) {
        VideoTracker tracker = VideoTracker.getInstance("GVD-200134", "GSD-200134", this);
        VideoTracker.setMfrs(android.os.Build.MANUFACTURER);
        VideoTracker.setDevice("android");
        VideoTracker.setChip(Build.VERSION.RELEASE);

        if (isLiving) {
            infoProvider = new ILiveInfoProvider() {
                @Override
                public double getFramesPerSecond() {
                    if (mediaPlayer != null) {
                        return mediaPlayer.getVideoDecodeFramesPerSecond();
                    }
                    return 0;
                }

                @Override
                public double getBitrate() {
                    if (mediaPlayer != null) {
                        return mediaPlayer.getBitRate();
                    }
                    return 0;
                }
            };
            play = tracker.newLivePlay(info, (ILiveInfoProvider) infoProvider);
        } else {
            infoProvider = new IVodInfoProvider() {
                @Override
                public double getPosition() {
                    if (mediaPlayer != null) {
                        return mediaPlayer.getCurrentPosition();
                    }
                    return 0;
                }

                @Override
                public double getFramesPerSecond() {
                    if (mediaPlayer != null) {
                        return mediaPlayer.getVideoDecodeFramesPerSecond();
                    }
                    return 0;
                }

                @Override
                public double getBitrate() {
                    if (mediaPlayer != null) {
                        return mediaPlayer.getBitRate();
                    }
                    return 0;
                }
            };
            play = tracker.newVodPlay(info, (IVodInfoProvider) infoProvider);
        }
    }

    public interface OnPlayerFullClickListener {
        void onFullClick(boolean isNormal);
    }
}
